package com.linln.admin.ws.service.impl;

import com.linln.admin.ws.domain.BusinessApi;
import com.linln.admin.ws.domain.Muban;
import com.linln.admin.ws.repository.BusinessApiRepository;
import com.linln.admin.ws.service.BusinessApiService;
import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author sh
 * @date 2023/01/06
 */
@Service
public class BusinessApiServiceImpl implements BusinessApiService {

    @Autowired
    private BusinessApiRepository businessApiRepository;

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    public BusinessApi getById(Long id) {
        return businessApiRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<BusinessApi> getPageList(Example<BusinessApi> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return businessApiRepository.findAll(example, page);
    }

    /**
     * 保存数据
     * @param businessApi 实体对象
     */
    @Override
    public BusinessApi save(BusinessApi businessApi) {
        return businessApiRepository.save(businessApi);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return businessApiRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public List<BusinessApi> getAllList() {

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("status", match -> match.exact());

        BusinessApi businessApi = new BusinessApi();
        businessApi.setStatus(StatusEnum.OK.getCode());
        // 获取数据列表
        Example<BusinessApi> example = Example.of(businessApi, matcher);

        List<BusinessApi> mubanList = businessApiRepository.findAll(example);
        if (CollectionUtils.isEmpty(mubanList)){
            return Lists.newArrayList();
        }
        return mubanList;
    }
}